<template>
  <div class="json-editor">
    <p @click="down"><img src="../../assets/img/down.png" /> <span>下载</span></p>
    <textarea ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
// 主题
import 'codemirror/theme/rubyblue.css'
// import 'codemirror/theme/monokai.css'
// 语言
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
// eslint-disable-next-line import/no-webpack-loader-syntax
// require('script-loader!jsonlint')
var FileSaver = require('file-saver')
export default {
  name: 'JsonEditor',
  /* eslint-disable vue/require-prop-types */
  props: ['value'],
  data () {
    return {
      jsonEditor: false
    }
  },
  watch: {
    value (value) {
      const editorValue = this.jsonEditor.getValue()
      if (value !== editorValue) {
        this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
      }
    }
  },
  mounted () {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true,
      mode: 'application/json',
      gutters: ['CodeMirror-lint-markers'],
      theme: 'rubyblue',
      readOnly: true,
      lint: true
    })

    this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
    this.jsonEditor.on('change', (cm) => {
      this.$emit('changed', cm.getValue())
      this.$emit('input', cm.getValue())
    })
  },
  methods: {
    down () {
      const data = this.value
      const blob = new Blob([data], { type: 'text/plain;charset=utf-8' })
      FileSaver.saveAs(blob, 'hahaha.txt')
    },
    getValue () {
      return this.jsonEditor.getValue()
    }
  }
}
</script>

<style lang="less" scoped>
.json-editor {
    width: 99% !important;
    height: 100%;
    margin: 0 auto 0;
  &>p{
    background-color: #fff;
    width: 99%;
    margin: 0 auto 0;
     display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 5px 0;
    img{
      width: 20px;
      margin: 0 5px;
    }
  }

  ::v-deep {
    .CodeMirror {
      height: auto;
      min-height: 300px;
    }

    .CodeMirror-scroll {
      min-height: 300px;
    }

    .cm-s-rubyblue span.cm-string {
      color: #f08047;
    }
  }

}
</style>
